package org.easy.tool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.easy.tool.common.FileIOUtil;
import org.easy.tool.common.StringUtil;
import org.easy.tool.common.TimeUtil;
import org.easy.tool.common.WebUtil;
import org.easy.tool.entity.Knowledge;
import org.easy.tool.entity.Problem;
import org.easy.tool.entity.ProblemKnowledge;
import org.easy.tool.entity.UserDetail;
import org.easy.tool.mapper.*;
import org.easy.tool.service.IProblem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题目实现
 *
 * @author Valley
 * @since 2024-09-04 22:51:14
 */
@Service
public class ProblemService extends ServiceImpl<ProblemMapper, Problem> implements IProblem {

    @Autowired
    ProblemKnowledgeMapper problemKnowledgeMapper;

    @Autowired
    FileRecordMapper fileRecordMapper;

    @Autowired
    KnowledgeMapper knowledgeMapper;

    @Autowired
    UserDetailMapper userDetailMapper;

    @Value("${westudy.file.url}") private String fileUrl;
    @Value("${westudy.file.img-dir}") private String imgDir;

    /**
     * 根据父id自动生成一个名字
     */
    private String createKnowledgeName(String knowledgeId) {
        String name = knowledgeMapper.selectById(knowledgeId).getName();
        LambdaQueryWrapper<Problem> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Problem::getTitle, name);
        List<Problem> list = list(wrapper);
        if (list.size() == 0) return name + "第1题";
        int max = 0;
        for (Problem problem : list) {
            String problemTitle = problem.getTitle();
            if (problemTitle.contains("第") && problemTitle.contains("题")) {
                String str = problemTitle.split("第")[1].split("题")[0];
                int sort = Integer.parseInt(str);
                if (max < sort) max = sort;
            }
        }
        return name + "第" + (max + 1) + "题";
    }

    @Override
    public String submitProblem(LinkedHashMap data) throws Exception {
        Problem problem = new Problem();
        String userId = WebUtil.getUserId();
        problem.setUserId(userId);
        Object titleObj = data.get("title");
        String title = "";
        String knowledgeId = "";
        if (StringUtil.isBlank(titleObj)) {
            knowledgeId = ((List<String>) data.get("knowledgeId")).get(0);
            title = createKnowledgeName(knowledgeId);
        } else {
            title = (String) data.get("title");
        }
        problem.setTitle(title);
        String type = (String) data.get("type");
        problem.setType(type);
        Object titleImg = data.get("titleImg");
        Object explainImg = data.get("explainImg");
        problem.setTitleImg(titleImg + "");
        problem.setExplainImg(explainImg + "");
        Object levelObj = data.get("levelObj");
        if (StringUtil.isBlank(levelObj)) {
            problem.setLevel(3);
        } else {
            problem.setLevel(Integer.parseInt(levelObj + ""));
        }
        problem.setCreateTime(TimeUtil.nowMS());
        problem.setUpdateTime(TimeUtil.nowMS());
        save(problem);
        ProblemKnowledge problemKnowledge = new ProblemKnowledge();
        problemKnowledge.setProblemId(problem.getId());
        problemKnowledge.setKnowledgeId(knowledgeId);
        problemKnowledge.setCreateTime(TimeUtil.nowMS());
        problemKnowledge.setUpdateTime(TimeUtil.nowMS());
        problemKnowledgeMapper.insert(problemKnowledge);
        return problem.getId();
    }

    @Override
    public List<Problem> getProblemList(LinkedHashMap data) {
        return new ArrayList<>();
    }

    @Override
    public boolean deleteProblem(LinkedHashMap data) throws Exception {
        String problemId = (String) data.get("problemId");
        //删除图片记录
        Problem problem = getById(problemId);
        fileRecordMapper.deleteById(problem.getTitleImg());
        fileRecordMapper.deleteById(problem.getExplainImg());
        //删除存储的文件
        String contentPath = imgDir + File.separator + problem.getTitleImg();
        FileIOUtil.delete(contentPath);
        String answerPath = imgDir + File.separator + problem.getExplainImg();
        FileIOUtil.delete(answerPath);
        //删除题目跟标签的关系
        boolean status = problemKnowledgeMapper.deleteByProblemId(problemId);
        return removeById(problemId) && status;
    }

    @Override
    public Object createEasyProblem(LinkedHashMap data) throws Exception {

        return null;
    }

    @Override
    public Object getEasyProblem(LinkedHashMap data) {
        Object knowledgeId = data.get("knowledgeId");

        return null;
    }

    @Override
    public Object getPageProblemList(LinkedHashMap data, List<List<String>> knowledgeSet) {
        Integer page = (Integer) data.get("page");
        Integer pageSize = (Integer) data.get("pageSize");
        // 创建分页对象（当前页码, 每页条数）
        Page<Problem> problemPage = new Page<>(page, pageSize);
        // 使用 LambdaQueryWrapper 构建查询（无条件）
        LambdaQueryWrapper<Problem> queryWrapper = new LambdaQueryWrapper<>();
        // 根据tags构造查询条件
        tagsCondition(knowledgeSet, queryWrapper);
        queryWrapper.orderByDesc(Problem::getUpdateTime);
        Page<Problem> result = page(problemPage, queryWrapper);
        LinkedHashMap resData = new LinkedHashMap();
        resData.put("total", result.getTotal());
        String userId = WebUtil.getUserId();
        List<LinkedHashMap> items = new ArrayList<>();
        for (Problem problem : result.getRecords()) {
            LinkedHashMap item = new LinkedHashMap();
            String problemId = problem.getId();
            item.put("id", problemId);
            item.put("title", problem.getTitle());
            item.put("images", new String[]{fileUrl + problem.getTitleImg(), fileUrl + problem.getExplainImg()});
            item.put("tags", getKnowledgeList(problem.getId()));
            UserDetail favorite = userDetailMapper.getUserDetail(userId, "favorite", problemId);
            if (favorite != null) item.put("isFavorite", true);
            UserDetail mistake = userDetailMapper.getUserDetail(userId, "mistake", problemId);
            if (mistake != null) item.put("isMistake", true);
            UserDetail comprehend = userDetailMapper.getUserDetail(userId, "comprehend", problemId);
            if (comprehend != null) item.put("isComprehend", true);
            items.add(item);
        }
        resData.put("items", items);
        return resData;
    }

    private List<Knowledge> getKnowledgeList(String problemId){
        List<Knowledge> knowledgeList = new ArrayList<>();
        List<String> knowledgeIdList = problemKnowledgeMapper.getIdByProblemId(problemId);
        if (knowledgeIdList.size() > 0){
            knowledgeList = knowledgeMapper.getListByIdList(knowledgeIdList);
        }
        return knowledgeList;
    }

    /**
     * 根据tags构造查询条件
     */
    private void tagsCondition(List<List<String>> knowledgeIdList, LambdaQueryWrapper<Problem> problemWrapper) {
        if (knowledgeIdList.size() == 0) return;
        List<List<String>> problemLists = new ArrayList<>();
        String userId = WebUtil.getUserId();
        for (List<String> list : knowledgeIdList) {
            if (list.contains("favorite")){
                //个人收藏
                List<UserDetail> favorite = userDetailMapper.getUserDetailListByType(userId, "favorite");
                problemLists.add(favorite.stream().map(UserDetail::getDetailId).collect(Collectors.toList()));
            } else if (list.contains("mistake")){
                //错题集
                List<UserDetail> favorite = userDetailMapper.getUserDetailListByType(userId, "mistake");
                problemLists.add(favorite.stream().map(UserDetail::getDetailId).collect(Collectors.toList()));
            } else if (list.contains("comprehend")){
                //已掌握
                List<UserDetail> favorite = userDetailMapper.getUserDetailListByType(userId, "comprehend");
                problemLists.add(favorite.stream().map(UserDetail::getDetailId).collect(Collectors.toList()));
            }else {
                //普通筛选项
                LambdaQueryWrapper<ProblemKnowledge> problemKnowledgeWrapper = new LambdaQueryWrapper<>();
                problemKnowledgeWrapper.in(ProblemKnowledge::getKnowledgeId, list);
                List<ProblemKnowledge> problemKnowledgeList = problemKnowledgeMapper.selectList(problemKnowledgeWrapper);
                problemLists.add(problemKnowledgeList.stream()
                        .map(ProblemKnowledge::getProblemId)
                        .collect(Collectors.toList()));
            }
        }
        //最终满足要求的题目id
        List<String> intersection = problemLists.stream()
                .reduce((listA, listB) -> {
                    Set<String> setB = new HashSet<>(listB);
                    return listA.stream()
                            .filter(setB::contains)
                            .collect(Collectors.toList());
                }).orElse(Collections.emptyList());
        if (intersection.size() == 0) {
            problemWrapper.apply("1 = 0");
        }else {
            problemWrapper.in(Problem::getId, intersection);
        }
    }

}
